
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#include "RTPrimTriangle.h"


#include <cstring>

#include "RTMatrix33.h"

namespace RT
{
	/*Default constructor*/
	RTPrimTriangle::RTPrimTriangle():RTIPrimitive()
	{
	}

	/*Constructor*/
	RTPrimTriangle::RTPrimTriangle(RTVector3f* v):RTIPrimitive()
	{
		//copy the vertices
		memcpy(m_vertex, v, 3*sizeof(RTVector3f));

		//calculate the normal
		m_normal = (m_vertex[1] - m_vertex[0]).cross(m_vertex[2] - m_vertex[0]);
		m_normal.normalize();
	}

	/*Constructor*/
	RTPrimTriangle::RTPrimTriangle(RTVector3f v1, RTVector3f v2, RTVector3f v3):RTIPrimitive()
	{
		//copy the vertices
		m_vertex[0] = v1;
		m_vertex[1] = v2;
		m_vertex[2] = v3;

		//calculate the normal
		m_normal = (m_vertex[1] - m_vertex[0]).cross(m_vertex[2] - m_vertex[0]);
		m_normal.normalize();
	}

	//destructor
	RTPrimTriangle::~RTPrimTriangle(){}

	//add a vertex
	void RTPrimTriangle::addVertex(const RTVector3f& v, I32 id)
	{
		m_vertex[id] = v;
	}

	//add a uv texture coordinate
	void RTPrimTriangle::addUV(const RTVector3f& v, I32 id)
	{
		m_UV[id] = v;
	}

	//set triangle's normal
	void RTPrimTriangle::setNormal(const RTVector3f& n)
	{
		m_normal = n;
	}

	//calculate the normal
	void RTPrimTriangle::computeNormal()
	{
		//calculate the normal
		m_normal = (m_vertex[1] - m_vertex[0]).cross(m_vertex[2] - m_vertex[0]);
		m_normal.normalize();
	}

	//precompute some value to make calculation faster
	void RTPrimTriangle::preCompute()
	{
		_useTranslation = false;

		//calculate D
		RTMatrix33 mD(m_vertex[0], m_vertex[1], m_vertex[2]); 
		_D = mD.det();

		//if D = 0, then the triangle is on the plane x=0 or y=0 or z=0 or a poI32 is on (0, 0, 0) so we translate everything
		_offset = RTVector3f(0, 0, 0);
		while (_D == 0)
		{
			_useTranslation = true;
			_offset = _offset + RTVector3f(1, 1, 1);
			_uvTranslated[0] = m_vertex[0] + _offset;
			_uvTranslated[1] = m_vertex[1] + _offset;
			_uvTranslated[2] = m_vertex[2] + _offset;
			mD.setColumns(_uvTranslated[0], _uvTranslated[1], _uvTranslated[2]); 
			_D = mD.det();
		}
	}

	//calculate if there is an intersection between the ray and the triangle. The ray must be in triangle local space.
	bool RTPrimTriangle::intersect(const RTRay& ray, F32& dist, bool useGlobalCoordinates)
	{
		//change the coordinate system
		RTRay modRay;
		if (useGlobalCoordinates)
			globalToLocal(ray, modRay);
		else
			convertRayToLocalCoordinates(ray, modRay);


		RTVector3f w(modRay.getOrigin().x - m_vertex[0].x, modRay.getOrigin().y - m_vertex[0].y, 
			modRay.getOrigin().z - m_vertex[0].z);

		RTVector3f u = m_vertex[1] - m_vertex[0];
		RTVector3f v = m_vertex[2] - m_vertex[0];

		F32 D = -(u.cross(v)).dot(modRay.getDirection());
		F32 a = -(w.cross(v)).dot(modRay.getDirection()) / D;
		F32 b = -(u.cross(w)).dot(modRay.getDirection()) / D;

		dist = (u.cross(v)).dot(w) / D;

		if(dist <= 0)
			return false;

		if(a > 0 && b > 0 && a+b <= 1)
			return true;

		return false;

	}

	//calculate if there is an intersection between the ray and the triangle. The ray must be in triangle local space.
	bool RTPrimTriangle::intersectLocalSpace(const RTRay& ray, F32& dist)
	{
		RTVector3f w(ray.getOrigin().x - m_vertex[0].x, ray.getOrigin().y - m_vertex[0].y, 
			ray.getOrigin().z - m_vertex[0].z);

		RTVector3f u = m_vertex[1] - m_vertex[0];
		RTVector3f v = m_vertex[2] - m_vertex[0];

		F32 D = -(u.cross(v)).dot(ray.getDirection());
		F32 a = -(w.cross(v)).dot(ray.getDirection()) / D;
		F32 b = -(u.cross(w)).dot(ray.getDirection()) / D;

		dist = (u.cross(v)).dot(w) / D;

		if(dist <= 0)
			return false;

		if(a > 0 && b > 0 && a+b <= 1)
			return true;

		return false;
	}

	/*Calculate the triangle's normal*/
	void RTPrimTriangle::computeNormal(const RTRay& ray, F32 /*dist*/, RTVector3f& normal)const
	{
		//change the coordinate system
		RTRay R;
		convertRayToLocalCoordinates(ray, R);

		normal = m_normal;
		//if(ray.getDirection().dot(normal) > 0)
		//	normal *= -1;

		convertNormalToGlobalCoordinates(normal, normal);
	}

	/*Check if the point is in the triangle*/
	bool RTPrimTriangle::isInside(const RTVector3f& p)const
	{
		//convert p to local coordinates
		RTVector3f localP;
		convertPointToLocalCoordinates(p, localP);

		if (sameSide(p, m_vertex[0], m_vertex[1], m_vertex[2]) && sameSide(p, m_vertex[1], m_vertex[0], m_vertex[2])
			&& sameSide(p, m_vertex[2], m_vertex[0], m_vertex[1])) 
			return true;
    
		return false;
	}

	//get a pointer to the vertex array
	RTVector3f* RTPrimTriangle::getVertices()
	{
		return m_vertex;
	}

	//get a pointer to the uv map array
	RTVector3f* RTPrimTriangle::getUV()
	{
		return m_UV;
	}

	/*Check if p1 is on the same side as the triangle normal*/
	bool RTPrimTriangle::sameSide(const RTVector3f& p1, const RTVector3f& p2, const RTVector3f& a, const RTVector3f& b)const
	{
		RTVector3f cp1 = (b-a).cross(p1-a);
		RTVector3f cp2 = (b-a).cross(p2-a);
		if(cp1.dot(cp2) >= 0)
			return true;

		return false;
	}
}